import getopt
import os
import sys
import re
import threading
from time import sleep, strftime, localtime

import pyautogui as pg
import pyperclip as cp

pg.FAILSAFE = True
pg.PAUSE = 0.2


def moveTo(im, region=None):
    try:
        if region:
            pg.moveTo(pg.locateCenterOnScreen(im, confidence=0.85, region=region))
        else:
            pg.moveTo(pg.locateCenterOnScreen(im, confidence=0.85))
        return True
    except:
        if im not in ('nomatch.png', 'login.png'):
            raise Exception(' 不能定位到' + str(im))


def write(str):
    cp.copy(str)
    pg.click()
    pg.hotkey('ctrl', 'a')
    sleep(1)
    pg.hotkey('ctrl', 'v')


def rms(res):
    return ''.join(res.split()) if res else ''


def valid(msg):
    pg.rightClick()
    pg.move(15, 15)
    pg.click()
    paste = cp.paste()
    if rms(paste) != rms(msg):
        pg.move(-15, -45)
        x, y = pg.position()
        if (y > 0):
            return valid(msg)
        else:
            return False
    else:
        return True


def emit(target, msg):
    pg.hotkey('ctrl', 'alt', 'w')

    if moveTo('search.png'):
        pg.move(30)
        write(target)
        sleep(1)
        if moveTo('nomatch.png'):
            raise Exception(' 找不到接收对象-' + str(target))
        pg.move(None, 80)
        pg.click()
        if moveTo('write.png'):
            write(msg)
            if moveTo('send.png'):
                pg.click()
                sleep(0.5)
                cp.copy('')
                pg.move(-30, -150)
                return valid(msg)


def send(target, msg):
    result = {'esSendStatus': 2, 'esResult': ''}
    if (target and msg):
        for i in range(3):
            print('The send times->', i + 1)
            try:
                if emit(target, msg):
                    result['esSendStatus'] = 1
                    break
            except Exception as error:
                result['esResult'] += '\n--第' + str(i + 1) + '次发送失败->' + str(error)
    else:
        result['esResult'] = "没有发送对象或消息"
    return result


def start_wx():
    try:
        wx = None
        try:
            wx = os.popen('tasklist |findstr WeChat').read()
        except:
            write_err('findstr WeChat exec failed!')

        if not wx:
            threading.Thread(target=lambda: os.system('"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe"')).start()
            sleep(2)
            if (moveTo('login.png')):
                pg.click()
                sleep(2)
                pg.screenshot('loginQR.png')
    except Exception as err:
        write_err(err)


def write_err(err):
    fo = open("error.log", "a")
    fo.write("\n" + strftime("%Y-%m-%d %H:%M:%S", localtime()) + " -> " + str(err))
    fo.close()


def main(argv):
    target = ''
    msg = ''
    try:
        opts, args = getopt.getopt(argv, "ht:m:", ["target=", "msg="])
    except getopt.GetoptError:
        print('sendwx.py -t <target> -m <msg>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('sendwx.py -t <target> -m <msg>')
            sys.exit()
        elif opt in ("-t", "--target"):
            target = arg
        elif opt in ("-m", "--msg"):
            msg = arg

    print(send(target, msg))


if __name__ == "__main__":
    main(sys.argv[1:])
